<template>
  <a-modal
    :visible="visible"
    width="800px"
    :closable="false"
    @ok="handleEditOk"
    @cancel="cancelHandel">
    <div>
      <a-row :gutter="24" >
        <a-col :span="8">
          <a-card :bordered="true" title="菜单树" :bodyStyle="bodyStyle" :headStyle="headStyle">
            <div>
              <a-tree
                checkable
                @expand="onExpand"
                :expandedKeys="expandedKeys"
                :autoExpandParent="autoExpandParent"
                v-model="checkedKeys"
                @select="selectMenuNode"
                @check="checkMenuNode"
                :treeData="treeData"
                :replaceFields="replaceFields"
              />
            </div>

          </a-card>
        </a-col>
        <a-col :span="16" >
          <a-card :bordered="true" title="按钮权限" :bodyStyle="bodyStyle" :headStyle="headStyle">
            <a-table
              ref="table"
              size="default"
              :columns="columns"
              :dataSource="elements"
              :alert="false"
              :rowKey="(record) => record.id"
              :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: elmentsChange }"
            ></a-table>
          </a-card>
        </a-col></a-row>
    </div>
  </a-modal>
</template>
<script>
import { query, method } from '@/api/admin'
import MenuTree from '@/components/admin/MenuTree'
export default {
  name: 'RoleAuth',
  components: {
    MenuTree
  },
  data () {
    return {
      visible: false,
      currentitem: '', // 点击菜单节点
      selectedRowKeys: [],
      selectedRows: [],
      bodyStyle: {
        padding: '12px',
        height: '480px',
        overflow: 'auto'
      },
      headStyle: {
        'margin-left': '20px',
        'margin-right': '20px',
        'margin-top': '15px'
      },
      elements: [],
      // 表头
      columns: [
        {
          title: '代码',
          dataIndex: 'code',
          key: 'code'
        },
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name'
        }
      ],
      action: [], // 当前点击的菜单节点
      role: {}, // 当前角色
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      treeData: [],
      replaceFields:
      {
        title: 'name', key: 'id'
      },
      halfCheckedKeys: [],
      changeStatue: false
    }
  },
  created () {
  },
  methods: {
    onExpand (expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    begin: function (role) {
      this.elements = []
      this.checkedKeys = []
      this.expandedKeys = []
      this.changeStatue = false
      this.role = role
      query('/admin/pmRole/permission', 'GET', { id: role.id }).then(res => {
        this.treeData = res.result.data
        this.resetCheckedKeys(this.treeData)
        this.resetNodeName(this.treeData)
      })
      this.visible = true
    },
    resetCheckedKeys (data) {
      data.forEach(item => {
        if (item.checkout !== true) {
          if (item.children) {
            this.resetCheckedKeys(item.children)
          }
        } else {
          const res = this.hasFalseChild(item.children)
          if (!res) {
            this.checkedKeys.push(item.id)
          } else {
            this.resetCheckedKeys(item.children)
          }
        }
      })
    },
    resetNodeName (data) {
      data.forEach(item => {
        item.name = item.meta.title
        if (item.children) {
          this.resetNodeName(item.children)
        }
      })
    },
    /**
     * 查看子集中是否存在checkout为false的元素
     */
    hasFalseChild (data) {
      return data.some(item => {
        if (item.checkout !== false) {
          if (item.children) {
            return this.hasFalseChild(item.children)
          }
        }
        return true
      })
    },
    /**
     * 点击菜单树节点
     */
    selectMenuNode (selectedKeys, e) {
      this.elements = e.selectedNodes[0] === undefined ? [] : e.selectedNodes[0].data.props.elements
      this.selectedRowKeys = this.elements.filter(item => item.defaultCheck === true).map(item => item.id)
    },
    /**
     * 点击菜单树节点的复选框
     */
    checkMenuNode (checkedKeys, e) {
      this.changeStatue = true
      this.halfCheckedKeys = e.halfCheckedKeys
    },
    /**
     * table-多选框的点击事件
     */
    elmentsChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.elements.forEach(x => {
        if (this.selectedRowKeys.indexOf(x.id) > -1) {
          x.defaultCheck = true
        } else {
          x.defaultCheck = false
        }
      })
    },
    /**
     * 发到后台的数据，根据后端的处理逻辑，将非全选节点checkout置为true
     */
    resetTreeData (data) {
      this.checkedKeys = this.checkedKeys.concat(this.halfCheckedKeys)
      data.forEach(menu => {
        const result = this.checkedKeys.some(item => {
          if (menu.id === item) {
            menu.checkout = true
            return true
          }
        })
        if (!result) {
          menu.checkout = false
        }
        if (menu.children) {
          this.resetTreeData(menu.children)
        }
      })
    },
    /**
     * 保存
     */
    handleEditOk () {
      // 当菜单权限发生变更时触发
      if (this.changeStatue) {
        this.resetTreeData(this.treeData)
      }
      const actionParam = {// 请求参数
        'url': '/admin/pmRole/permission',
        'action': 'PUT',
        'parameter': {},
        'data': Object.assign({}, { 'id': this.role.id, 'permissionList': this.treeData }),
        'message': '操作成功'
      }
      method(actionParam).then(res => {
        this.visible = false
      })
    },
    /**
     * 关闭弹出框
     */
    close () {
      this.id = null
      this.visible = false
    },
    /**
     * 取消操作
     */
    cancelHandel () {
      this.close()
    }
  }
}
</script>
<style>

</style>
